package com.xyrl.third.aliyun.service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dypnsapi.model.v20170525.GetMobileRequest;
import com.aliyuncs.dypnsapi.model.v20170525.GetMobileResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.xyrl.third.aliyun.config.AliYunProperties;
import com.xyrl.third.aliyun.constant.AliYunConstant;
import com.xyrl.third.aliyun.exception.AliYunException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 阿里 取得手机号码工具
 *
 * @author zhongp
 * @version 1.0
 * @className MobileService
 * @company 星纭融链科技服务有限公司
 * @date 2020-01-02 17:06:47
 * @Description
 */
@Slf4j
public class MobileService {

    @Autowired
    private AliYunProperties aliYunProperties;

    /**
     * 根据移动端传入的token 取得手机号码
     *
     * @param token
     * @author zhongp
     * @date 2020-01-02 17:07:59
     * @description https://api.aliyun.com/new?spm=a2c4g.11186623.2.12.651c7861c35dBX#/?product=Dypnsapi&api=GetMobile&params={%22RegionId%22:%22cn-hangzhou%22}&tab=DEMO&lang=JAVA
     */
    public GetMobileResponse getMobile(String token) throws AliYunException {
        DefaultProfile profile = DefaultProfile.getProfile(aliYunProperties.getRegionId(), aliYunProperties.getAccessKeyId(), aliYunProperties.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);

        GetMobileRequest request = new GetMobileRequest();
        request.setSysRegionId(aliYunProperties.getRegionId());
        request.setAccessToken(token);
        try {
            GetMobileResponse response = client.getAcsResponse(request);
            log.debug("阿里一键登录返回结果:{}",request);
            return response;
        } catch (ServerException e) {
            log.error("一键登录取得手机号码异常", e);
            throw new AliYunException(e.getMessage());
        } catch (ClientException e) {
            log.error("ErrCode:" + e.getErrCode());
            log.error("ErrMsg:" + e.getErrMsg());
            log.error("RequestId:" + e.getRequestId());
            log.error("一键登录取得手机号码异常", e);
            throw new AliYunException(e.getMessage());
        }
    }
}
